import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../resource/language/generated/l10n.dart';
import '../widget/textfield/jr_text_field.dart';
import 'user_feedback_model.dart';
import 'view_big_video.dart';

class JRDialogUserFeedback extends StatefulWidget {
  JRDialogUserFeedback({Key? key}) : super(key: key);

  static show(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        useRootNavigator: false,
        builder: (_) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16.0)),
              backgroundColor: Colors.transparent,
              insetPadding: EdgeInsets.zero,
              child: Builder(builder: (context) {
                return MultiProvider(providers: [
                  ChangeNotifierProvider(create: (_) => UserFeedbackModel()),
                ], child: JRDialogUserFeedback());
              }));
        });
  }

  @override
  State<JRDialogUserFeedback> createState() => _JRDialogUserFeedbackState();
}

class _JRDialogUserFeedbackState extends State<JRDialogUserFeedback> {
  String value = "";

  var type = 0;

  Widget get typeButton => Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            T.current.issue_type,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: Color(0xff666666),
            ),
          ),
          DropdownButton<int>(
              items: [
                DropdownMenuItem<int>(
                  value: 0,
                  child: Text(T.current.def),
                ),
                DropdownMenuItem<int>(
                  value: 1,
                  child: Text(T.current.live_audio),
                ),
              ],
              value: type,
              onChanged: (_) {
                type = _ ?? 0;
                setState(() {});
              }),
        ],
      );

  @override
  Widget build(BuildContext context) {
    return Consumer<UserFeedbackModel>(
        builder: (BuildContext context, UserFeedbackModel model, child) {
      return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.w),
        ),
        margin: EdgeInsets.symmetric(horizontal: 37.5.w),
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 24.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 36.h,
            ),
            Text(
              T.current.user_feedback,
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Color(0xff333333),
                height: 18 / 18,
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: typeButton,
            ),
            const SizedBox(
              height: 24,
            ),
            GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                  childAspectRatio: 1),
              itemBuilder: (BuildContext context, int index) {
                var length = model.reportImages.length;
                if (length == index) {
                  return GestureDetector(
                    onTap: () {
                      model.uploadPicture(context, index);
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        color: const Color(0xFFF6F7F9),
                      ),
                      child: const Icon(
                        Icons.add,
                        color: Color(0xFFBBBBBB),
                      ),
                    ),
                  );
                }
                return model.reportImages[index]['type'] == AssetType.image
                    ? GestureDetector(
                        onTap: () {
                          // JrImageView.show(
                          //   context,
                          //   model.reportImages
                          //       .where((element) =>
                          //           element['type'] == AssetType.image)
                          //       .map<ImageItem>(
                          //           (e) => ImageItem(e['data'], true))
                          //       .toList(),
                          //   index,
                          //   onDelete: (url) async {
                          //     model.reportImages.removeWhere(
                          //         (element) => element['data'] == url);
                          //     model.notifyListeners();
                          //     return true;
                          //   },
                          // );
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            color: const Color(0xFFF6F7F9),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8.0),
                            child: Image.network(
                                model.reportImages[index]['data']),
                          ),
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          Navigator.of(context).push(
                            CupertinoPageRoute(
                              builder: (context) {
                                return ViewBigVideo(
                                  model.reportImages[index]['data'],
                                  (url) {
                                    model.reportImages.removeWhere(
                                        (element) => element['data'] == url);
                                    model.notifyListeners();
                                    return true;
                                  },
                                );
                              },
                            ),
                          );
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            color: const Color(0xFFF6F7F9),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8.0),
                            child: Image.memory(
                                model.reportImages[index]['thumb']),
                          ),
                        ),
                      );
              },
              itemCount: model.reportImages.length >= 4
                  ? 4
                  : model.reportImages.length + 1,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: Text(
                T.current.please_input_face_issue,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  color: Color(0xff666666),
                  height: 22 / 14,
                ),
              ),
            ),
            JRTextField(
                hintText: T.current.input_your_issue,
                onChanged: (value) {
                  this.value = value;
                }),
            SizedBox(
              height: 28.h,
            ),
            Row(
              children: [
                Expanded(
                    child: CupertinoButton(
                  onPressed: () async {
                    Navigator.pop(context);
                  },
                  minSize: 0,
                  padding: EdgeInsets.zero,
                  child: Container(
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Color(0xfff6f7f9),
                      borderRadius: BorderRadius.circular(26.h),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      T.current.cancel,
                      style: TextStyle(
                        fontSize: 15.sp,
                        fontWeight: FontWeight.w500,
                        color: Color(0xff666666),
                        height: 15 / 15,
                      ),
                    ),
                  ),
                )),
                SizedBox(
                  width: 12.w,
                ),
                Expanded(
                    child: CupertinoButton(
                  onPressed: () async {
                    uploadAgoraLog();
                    // var create = ReportFeedbackReq(desc: value);
                    // create.evidenceImages.addAll(model.reportImages
                    //     .where((element) => element['type'] == AssetType.image)
                    //     .where(
                    //         (element) => !CBStringUtil.isEmpty(element['data']))
                    //     .map((e) => e['data'] as String));
                    // create.evidenceVideos.addAll(model.reportImages
                    //     .where((element) => element['type'] == AssetType.video)
                    //     .where(
                    //         (element) => !CBStringUtil.isEmpty(element['data']))
                    //     .map((e) => EvidenceVideos(
                    //         thumb: e['thumbUrl'] ?? '', url: e['data'])));
                    // ReportApi.instance.postReportUserFeedback(create);
                    Navigator.pop(context);
                  },
                  minSize: 0,
                  padding: EdgeInsets.zero,
                  child: Container(
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Color(0xffffd400),
                      borderRadius: BorderRadius.circular(26.h),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      T.current.surer,
                      style: TextStyle(
                        fontSize: 15.sp,
                        fontWeight: FontWeight.w500,
                        color: Color(0xff333333),
                        height: 15 / 15,
                      ),
                    ),
                  ),
                )),
              ],
            ),
            SizedBox(
              height: 32.h,
            ),
          ],
        ),
      );
    });
  }

  Future<void> uploadAgoraLog() async {
    if (type != 1) return;

    var fileDir = await getExternalStorageDirectory();
    var files = fileDir?.listSync();

    files?.forEach((_) async {
      // if (_.name.startsWith('agora')) {
      //   await TosUploadUtils.uploadByTos(localFilePath: _.path, sceneCode: 105);
      //   RLog.d('Finished upload agora log: ${_.name}');
      // }
    });
  }
}
